package com.kly.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.kly.api.ai.AliYunAiApi;
import com.kly.api.ai.model.CreateImageOutPaintingResponse;
import com.kly.api.ai.model.GetImageOutPaintingResponse;
import com.kly.api.ai.model.ImageOutPaintingRequest;
import com.kly.api.imagesearch.model.SoImageSearchResult;
import com.kly.api.imagesearch.sub.SoImageSearchApiFacade;
import com.kly.common.PageRequest;
import com.kly.constants.UserConstant;
import com.kly.domain.dto.file.UploadPictureResult;
import com.kly.domain.dto.pircture.*;
import com.kly.domain.dto.user.TopThumbUserRequest;
import com.kly.domain.entity.*;
import com.kly.domain.enums.ExpansionStatus;
import com.kly.domain.enums.ReviewStatusEnum;
import com.kly.domain.vo.PictureTagCategory;
import com.kly.domain.vo.PictureVO;
import com.kly.domain.vo.UserVO;
import com.kly.exception.BusinessException;
import com.kly.exception.ErrorCode;
import com.kly.exception.ThrowUtils;
import com.kly.manager.CosManager;
import com.kly.manager.auth.StpKit;
import com.kly.manager.upload.FilePictureUpload;
import com.kly.manager.upload.PictureUploadTemplate;
import com.kly.manager.upload.UrlPictureUpload;
import com.kly.mapper.PictureMapper;
import com.kly.service.*;
import com.kly.utils.ColorSimilarUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

import static com.kly.constants.RedisConstant.*;

/**
 * @author admin
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-03-03 20:07:13
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {

    @Resource
    private UserService userService;


    @Resource
    private UrlPictureUpload urlPictureUpload;

    @Resource
    private FilePictureUpload filePictureUpload;
    @Resource
    private CosManager cosManager;

    @Resource
    private SpaceService spaceService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserFollowService userFollowService;

    @Resource
    private ImageExpansionService imageExpansionService;

    @Resource
    private AliYunAiApi aliyunAiApi;



    @Override
    public PictureVO savePicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        ThrowUtils.throwIf(inputSource == null, ErrorCode.PARAMS_ERROR, "上传文件不能为空");
        Long id = null;
        Long spaceId = null;
        if (pictureUploadRequest != null) {
            id = pictureUploadRequest.getId();
            spaceId = pictureUploadRequest.getSpaceId();
        }

        // 查询空间
        Long userId = loginUser.getId();
        // 公有空间
        // 校验空间是否存在
        if (spaceId != null) {
            Space spaceDb = spaceService.getById(spaceId);
            ThrowUtils.throwIf(spaceDb == null, ErrorCode.PARAMS_ERROR, "空间不存在");
            //     只有空间管理员可以上传
            ThrowUtils.throwIf(!userId.equals(spaceDb.getUserId()), ErrorCode.NO_AUTH_ERROR, "没有权限");

            // 校验额度
            ThrowUtils.throwIf(spaceDb.getTotalCount() >= spaceDb.getMaxCount(), ErrorCode.OPERATION_ERROR, "空间额度不足");
            ThrowUtils.throwIf(spaceDb.getTotalSize() >= spaceDb.getMaxSize(), ErrorCode.OPERATION_ERROR, "空间额度不足");
        }


        // 查询数据库
        if (id != null) {
            // 更新操作
            Picture pictureDb = this.lambdaQuery()
                    .eq(Picture::getId, id).one();
            ThrowUtils.throwIf(pictureDb == null, ErrorCode.PARAMS_ERROR, "图片不存在");

            //     判断用户是否有权限
            if (!userId.equals(pictureDb.getUserId()) && !UserConstant.ADMIN_ROLE.equals(loginUser.getUserRole())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限");
            }

            //     判断spaceId
            if (spaceId == null) {
                spaceId = pictureDb.getSpaceId();
            } else {
                ThrowUtils.throwIf(!spaceId.equals(pictureDb.getSpaceId()), ErrorCode.PARAMS_ERROR, "空间id不匹配");
            }

            //     更新图片 删除旧图片
            deletePictureCos(pictureDb);
        }

        // 设置存储路径
        String uploadPathPrefix;

        if (spaceId != null) {
            uploadPathPrefix = String.format("space/%s", spaceId);
        } else {
            uploadPathPrefix = String.format("public/%s", userId);
        }

        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }

        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadFile(inputSource, uploadPathPrefix);


        ThrowUtils.throwIf(uploadPictureResult == null, ErrorCode.OPERATION_ERROR, "上传失败");
        // 拷贝
        Picture picture = BeanUtil.copyProperties(uploadPictureResult, Picture.class);
        picture.setUserId(userId);
        picture.setSpaceId(spaceId);
        // 设置名称
        String picName = null;
        if (pictureUploadRequest != null) {
            picName = pictureUploadRequest.getPicName();
        }
        if (StrUtil.isBlank(picName)) {
            picName = uploadPictureResult.getPicName();
        }
        picture.setName(picName);
        // 设置分类
        String category = null;
        if (pictureUploadRequest != null) {
            category = pictureUploadRequest.getCategory();
        }
        if (StrUtil.isBlank(category)) {
            category = "默认分类";
        }
        picture.setCategory(category);
        // 设置标签
        List<String> tags = null;
        if (pictureUploadRequest != null) {
            tags = pictureUploadRequest.getTags();
        }
        if (CollUtil.isEmpty(tags)) {
            tags = List.of("默认标签");
        }
        picture.setTags(JSONUtil.toJsonStr(tags));
        // 审核字段
        fillReviewInfo(picture, loginUser);

        // 判断是否是更新
        if (id != null) {
            picture.setId(id);
            picture.setEditTime(new Date());
        }
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            // 更新或保存
            boolean save = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR, "保存失败");
            if (finalSpaceId != null) {
                // 更新空间
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("total_count = total_count + 1")
                        .setSql("total_size = total_size  + " + picture.getPicSize())
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "更新空间失败");
            }

            // 推送消息到粉丝redis
            // 查询粉丝id
            List<Long> followingIdList = userFollowService.lambdaQuery()
                    .eq(UserFollow::getFollowedUserId, userId)
                    .list()
                    .stream()
                    .map(UserFollow::getFollowingUserId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(followingIdList)) {
                for (Long followingId : followingIdList) {
                    String key = PICTURE_FEED_KEY + followingId;
                    // 推送消息
                    stringRedisTemplate.opsForZSet().add(key, picture.getId().toString(), System.currentTimeMillis());
                }
            }
            return true;
        });
        return PictureVO.objToVo(picture);
    }

    private void validUrlInfo(String fileUrl) {
        int ONE_M = 1024 * 1024;
        // 1. 校验url
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "url不能为空");
        //     2. 校验url是否合法
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "url不合法");
        }
        // 校验域名
        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"), ErrorCode.PARAMS_ERROR, "url不合法");
        //     3. 校验文件是否存在
        HttpResponse response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
        if (!response.isOk()) {
            response = HttpUtil.createRequest(Method.GET, fileUrl).execute();
            ThrowUtils.throwIf(!response.isOk(), ErrorCode.PARAMS_ERROR, "解析文件出错，图片不存在");
        }
        //     4. 校验文件是否是图片
        String header = response.header("Content-Type");
        final List<String> IMAGE_FORMATS = Arrays.asList("image/jpeg", "image/webp", "image/png", "image/gif", "image/jpg", "application/octet-stream", "application/xml");
        ThrowUtils.throwIf(!IMAGE_FORMATS.contains(header), ErrorCode.PARAMS_ERROR, "文件格式不正确");
        //     5, 校验文件大小
        String lengthStr = response.header("Content-Length");
        ThrowUtils.throwIf(StrUtil.isBlank(lengthStr), ErrorCode.PARAMS_ERROR, "文件大小不合适");
        long length = Long.parseLong(lengthStr);
        ThrowUtils.throwIf(length > 5 * ONE_M, ErrorCode.PARAMS_ERROR, "图片内容过大");

    }

    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        // 审核信息
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        // 空间字段
        Long spaceId = pictureQueryRequest.getSpaceId();
        // 默认值
        Boolean nullSpaceId = Optional.ofNullable(pictureQueryRequest.getNullSpaceId()).orElse(Boolean.FALSE);
        // 开始，结束时间
        Date beginTime = pictureQueryRequest.getBeginTime();
        Date endTime = pictureQueryRequest.getEndTime();
        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "user_id", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "pic_format", picFormat);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.gt(ObjUtil.isNotEmpty(picWidth), "pic_width", picWidth);
        queryWrapper.gt(ObjUtil.isNotEmpty(picHeight), "pic_height", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "pic_size", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "pic_scale", picScale);

        // 审核字段
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "review_status", reviewStatus);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "review_message", reviewMessage);
        // 空间字段
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "space_id", spaceId);
        queryWrapper.isNull(nullSpaceId, "space_id");
        // 开始结束时间
        queryWrapper.ge(ObjUtil.isNotEmpty(beginTime), "create_time", beginTime);
        queryWrapper.lt(ObjUtil.isNotEmpty(endTime), "create_time", endTime);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }


    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR, "图片不存在");
        PictureVO pictureVO = PictureVO.objToVo(picture);
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User userDb = userService.getById(userId);
            UserVO userVo = userService.getUserVo(userDb);
            pictureVO.setUser(userVo);
        }
        return pictureVO;
    }

    @Override
    public void validatePictureInfo(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    @Override
    public Page<PictureVO> listPictureVOByPage(Page<Picture> page) {
        List<Picture> pictureList = page.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(page.getCurrent(), page.getSize());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 封装数据
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 关联用户信息
        // 1. 获取用户ids 不重复
        Set<Long> ids = pictureVOList.stream().map(PictureVO::getUserId).collect(Collectors.toSet());
        // 2. 获取用户表map形式 id, user
        Map<Long, List<User>> idMapUserList = userService.listByIds(ids).stream().collect(Collectors.groupingBy(User::getId));

        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            if (idMapUserList.containsKey(userId)) {
                List<User> userList = idMapUserList.get(userId);
                User user = userList.get(0);
                UserVO userVO = userService.getUserVo(user);
                pictureVO.setUser(userVO);
                setThumb(pictureVO, userId);
            }
        });
        pictureVOPage.setRecords(pictureVOList);
        pictureVOPage.setTotal(page.getTotal());
        return pictureVOPage;
    }

    @Override
    public boolean reviewPicture(PictureReviewRequest pictureReviewRequest, User loginUser) {
        // 1. 参数校验
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        String reviewMessage = pictureReviewRequest.getReviewMessage();
        ThrowUtils.throwIf(id <= 0 || reviewStatus == null || reviewStatus < 0 || reviewStatus > 2 || StrUtil.isBlank(reviewMessage), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null || loginUser.getId() == null, ErrorCode.NOT_LOGIN_ERROR);
        // 2. 获取图片信息
        Picture pictureDb = this.getById(id);
        // 只有待审核才可以审核
        if (pictureDb == null || !ReviewStatusEnum.getEnum(pictureDb.getReviewStatus()).equals(ReviewStatusEnum.UNREVIEWED)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片不存在或状态错误");
        }
        // 3. 更新图片状态
        Picture picture = BeanUtil.copyProperties(pictureReviewRequest, Picture.class);
        // 设置审核人 审核时间
        picture.setReviewerId(loginUser.getId());
        picture.setReviewTime(new Date());
        return this.updateById(picture);
    }


    /**
     * 填充审核信息
     */
    @Override
    public void fillReviewInfo(Picture picture, User loginUser) {
        // 填充审核信息
        // 判断是不是管理员
        if (UserConstant.ADMIN_ROLE.equals(loginUser.getUserRole())) {
            picture.setReviewStatus(ReviewStatusEnum.PASSED.getValue());
            picture.setReviewMessage("自动审核通过");
            picture.setReviewerId(loginUser.getId());
            picture.setReviewTime(new Date());
        } else {
            //     待审核
            picture.setReviewStatus(ReviewStatusEnum.UNREVIEWED.getValue());
        }
    }

    public ThreadPoolExecutor getThreadPoolExecutor() {
        return new ThreadPoolExecutor(
                10,
                20,
                1,
                TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(20)
        );
    }

    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        // 格式化数量 最多30条
        Integer count = pictureUploadByBatchRequest.getCount();
        if (count > 10) {
            count = 10;
        }
        // 获取线程池
        ThreadPoolExecutor threadPoolExecutor = this.getThreadPoolExecutor();
        CountDownLatch countDownLatch = new CountDownLatch(count);
        CompletableFuture.supplyAsync(() -> {
            // 要抓取的地址
            String fetchUrl = String.format("https://cn.bing.com/images/search?q=%s&mmasync=1", pictureUploadByBatchRequest.getSearchText());
            // 开始抓取
            Document document = null;
            try {
                document = Jsoup.connect(fetchUrl).get();
            } catch (IOException e) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片抓取失败");
            }
            Element div = document.getElementsByClass("dgControl").first();
            ThrowUtils.throwIf(div == null, ErrorCode.PARAMS_ERROR, "未找到图片");
            Elements imgElementList = div.select("img.mimg");
            // 遍历图片
            for (Element imgElement : imgElementList) {
                String src = imgElement.attr("src");
                if (StrUtil.isBlank(src)) {
                    log.error("图片地址为空");
                    continue;
                }
                //     处理图片上传地址 ？
                String fileUrl = src.substring(0, src.indexOf("&"));

                PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
                pictureUploadRequest.setFileUrl(fileUrl);

                String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
                if (StrUtil.isNotBlank(namePrefix)) {
                    pictureUploadRequest.setPicName(namePrefix + "_" + countDownLatch.getCount());
                }
                // 设置分类
                pictureUploadRequest.setCategory(pictureUploadByBatchRequest.getCategory());
                // 设置标签
                pictureUploadRequest.setTags(pictureUploadByBatchRequest.getTags());

                try {
                    //     上传图片
                    PictureVO pictureVO = this.savePicture(fileUrl, pictureUploadRequest, loginUser);

                    if (pictureVO != null) {
                        log.info("图片上传成功: url: {} id: {}", pictureVO.getUrl(), pictureVO.getId());
                        countDownLatch.countDown();
                    }
                } catch (Exception e) {
                    log.error("图片上传失败");
                    continue;
                }

                if (countDownLatch.getCount() == 0) {
                    break;
                }

            }
            return countDownLatch.getCount();
        }, threadPoolExecutor);


        return count;
    }

    @Async
    @Override
    public void deletePictureCos(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        String fileUrl = picture.getUrl();
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getUrl, fileUrl)
                .list();
        if (pictureList.size() > 1) {
            return;
        }
        cosManager.deletePictureObject(fileUrl);
        //     清理缩略图
        String thumbnailUrl = picture.getThumbnailUrl();
        if (StrUtil.isNotBlank(thumbnailUrl)) {
            cosManager.deletePictureObject(thumbnailUrl);
        }

        //     清除原图
        String originalUrl = picture.getOriginalUrl();
        if (StrUtil.isNotBlank(originalUrl)) {
            cosManager.deletePictureObject(originalUrl);
        }


    }


    @Override
    public void checkSpaceAuth(Picture picture, User loginUser) {
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR, "没有权限");
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR, "图片不存在");
        Long spaceId = picture.getSpaceId();

        if (spaceId != null) {
            //     私有空间
            // 空间管理员
            if (!loginUser.getId().equals(picture.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限");
            }
        } else {
            //     判断用户是否为创建人或管理员
            if (!loginUser.getId().equals(picture.getUserId()) && !UserConstant.ADMIN_ROLE.equals(loginUser.getUserRole())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限");
            }
        }
    }

    @Override
    public List<PictureVO> searchPictureByColor(SearchPictureByColorRequest searchPictureByColorRequest, User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        String picColor = searchPictureByColorRequest.getPicColor();
        // 转换color格式
        ThrowUtils.throwIf(StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR, "颜色不能为空");
        // 2. 判断权限 判断用户是否为创建人
        Space spaceDb = spaceService.getById(spaceId);
        if (!loginUser.getId().equals(spaceDb.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限");
        }
        // 3. 查询图片
        List<Picture> pictureList = this.lambdaQuery().eq(ObjectUtil.isNotEmpty(spaceId), Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        if (CollectionUtils.isEmpty(pictureList)) {
            return Collections.emptyList();
        }
        // 4. 计算相似度，并排序
        List<Picture> sortPictureList = pictureList.stream()
                .sorted(Comparator.comparingDouble(picture -> {
                    double similarity = ColorSimilarUtils.calculateSimilarity(picColor, picture.getPicColor());
                    return -similarity;
                })).limit(12)
                .collect(Collectors.toList());
        // 5. 返回结果
        return sortPictureList.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
    }

    private int count = 1;

    @Override
    public boolean editPictureBatch(PictureEditBatchRequest pictureEditBatchRequest, User loginUser) {
        ThrowUtils.throwIf(pictureEditBatchRequest == null, ErrorCode.PARAMS_ERROR);
        List<Long> idList = pictureEditBatchRequest.getIdList();
        Long spaceId = pictureEditBatchRequest.getSpaceId();
        String nameRule = pictureEditBatchRequest.getNameRule();
        String introduction = pictureEditBatchRequest.getIntroduction();
        String category = pictureEditBatchRequest.getCategory();
        List<String> tags = pictureEditBatchRequest.getTags();
        // 1. 检验参数
        ThrowUtils.throwIf(CollUtil.isEmpty(idList), ErrorCode.PARAMS_ERROR, "id不能为空");
        ThrowUtils.throwIf(spaceId == null, ErrorCode.PARAMS_ERROR, "spaceId不能为空");
        // 2. 判断权限 判断用户是否为创建人
        Space spaceDb = spaceService.getById(spaceId);
        if (!loginUser.getId().equals(spaceDb.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限");
        }
        // 3. 获取更新的原图片id，spaceId
        List<Picture> pictureListDb = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .in(Picture::getId, idList)
                .eq(Picture::getSpaceId, spaceId)
                .list();
        // 条数过多不允许
        ThrowUtils.throwIf(pictureListDb.size() > 5, ErrorCode.PARAMS_ERROR, "图片数量过多");
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureListDb), ErrorCode.PARAMS_ERROR, "图片不存在");
        // 4. 填充命名规则信息
        for (int i = 0; i < pictureListDb.size(); i++) {
            Picture picture = pictureListDb.get(i);
            fillNameRuleInfo(picture, nameRule, i + 1);
            picture.setIntroduction(introduction);
            picture.setCategory(category);
            //     tags转为json
            picture.setTags(JSONUtil.toJsonStr(tags));
        }
        // 5. 更新图片信息
        return this.updateBatchById(pictureListDb);
    }

    @Override
    public CreateImageOutPaintingResponse createImageOutPainting(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(createPictureOutPaintingTaskRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = Optional.ofNullable(createPictureOutPaintingTaskRequest.getPictureId()).orElseThrow(() -> new BusinessException(ErrorCode.PARAMS_ERROR, "图片id不能为空"));
        ImageOutPaintingRequest imageOutPaintingRequest = new ImageOutPaintingRequest();
        ImageOutPaintingRequest.Input input = new ImageOutPaintingRequest.Input();
        // 2. 获取图片信息
        Picture pictureDb = this.getById(pictureId);
        // 2.1权限校验
        checkSpaceAuth(pictureDb, loginUser);
        // 2.2 校验次数
        Long userId = loginUser.getId();
        User userDb = userService.getById(userId);
        Integer expandCount = userDb.getExpandCount();
        ThrowUtils.throwIf(expandCount < 1, ErrorCode.OPERATION_ERROR, "次数不足");

        // 3. 设置参数
        input.setImageUrl(pictureDb.getUrl());
        imageOutPaintingRequest.setInput(input);
        // 4. 调用接口
        BeanUtils.copyProperties(createPictureOutPaintingTaskRequest, imageOutPaintingRequest);
        CreateImageOutPaintingResponse imageOutPainting = aliYunAiApi.createImageOutPainting(imageOutPaintingRequest);
        // 判断是否成功
        if (StrUtil.isBlank(imageOutPainting.getCode())) {
            // 乐观锁 次数减一
            boolean update = userService.lambdaUpdate()
                    .eq(User::getId, userId)
                    .eq(User::getExpandCount, expandCount)
                    .setSql("expand_count = expand_count - 1")
                    .update();
            ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "次数不足");
        }

        // 5. 处理结果
        return imageOutPainting;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public CreateImageOutPaintingResponse createImageOutPainting(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest) {
        // 1. 校验参数
        ThrowUtils.throwIf(createPictureOutPaintingTaskRequest == null, ErrorCode.PARAMS_ERROR);
        ImageOutPaintingRequest imageOutPaintingRequest = new ImageOutPaintingRequest();
        ImageOutPaintingRequest.Input input = new ImageOutPaintingRequest.Input();
        // 2. 获取图片信息
        String fileUrl = createPictureOutPaintingTaskRequest.getFileUrl();
        validUrlInfo(fileUrl);
        // 2.2 校验次数
        long userId = StpKit.SPACE.getLoginIdAsLong();
        User userDb = userService.getById(userId);
        Integer expandCount = userDb.getExpandCount();
        ThrowUtils.throwIf(expandCount < 1, ErrorCode.OPERATION_ERROR, "次数不足");

        // 3. 设置参数
        input.setImageUrl(fileUrl);
        imageOutPaintingRequest.setInput(input);
        // 4. 调用接口
        BeanUtils.copyProperties(createPictureOutPaintingTaskRequest, imageOutPaintingRequest);
        CreateImageOutPaintingResponse imageOutPainting = aliYunAiApi.createImageOutPainting(imageOutPaintingRequest);
        // 判断是否成功
        if (StrUtil.isBlank(imageOutPainting.getCode())) {
            // 乐观锁 次数减一
            boolean update = userService.lambdaUpdate()
                    .eq(User::getId, userId)
                    .eq(User::getExpandCount, expandCount)
                    .setSql("expand_count = expand_count - 1")
                    .update();
            ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "次数不足");
        }
        String taskId = imageOutPainting.getOutput().getTaskId();
        // 保存扩图任务
        ImageExpansion imageExpansion = new ImageExpansion();
        imageExpansion.setOriginalPictureUrl(fileUrl);
        imageExpansion.setTaskId(taskId);
        imageExpansion.setUserId(userId);
        boolean save = imageExpansionService.save(imageExpansion);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR, "扩图任务保存失败");

        // 5. 处理结果
        return imageOutPainting;
    }

    @Override
    public boolean doThumbPicture(PictureThumbRequest pictureThumbRequest, User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(pictureThumbRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = pictureThumbRequest.getId();
        ThrowUtils.throwIf(pictureId == null, ErrorCode.PARAMS_ERROR);
        Long userId = loginUser.getId();
        ThrowUtils.throwIf(userId == null, ErrorCode.NOT_LOGIN_ERROR);
        // 查询数据库
        Picture pictureDb = this.getById(pictureId);
        ThrowUtils.throwIf(pictureDb == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        Long likeCount = Optional.ofNullable(pictureDb.getLikeCount()).orElse(0L);
        // 2. 判断用户是否已经点赞
        String key = PICTURE_LIKE_KEY + pictureId;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        // 3. 未点赞
        if (ObjUtil.isNull(score)) {
            // 3.1 更新数据库like_count
            boolean update = this.lambdaUpdate()
                    .eq(Picture::getId, pictureId)
                    .eq(Picture::getLikeCount, likeCount)
                    .setSql("like_count = like_count + 1")
                    .update();
            // 3.2 存储到redis
            if (update) {
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            // 4.1 更新数据库is_liked
            boolean update = this.lambdaUpdate()
                    .eq(Picture::getId, pictureId)
                    .eq(Picture::getLikeCount, likeCount)
                    .setSql("like_count = like_count - 1")
                    .update();
            // 4.2 删除redis
            if (update) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return true;
    }

    @Override
    public void setThumb(PictureVO pictureVO, Long userId) {
        if (userId == null) {
            return;
        }
        // 2. 判断用户是否已经点赞
        String key = PICTURE_LIKE_KEY + pictureVO.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        pictureVO.setIsLike(ObjUtil.isNotNull(score));
    }

    @Override
    public List<User> getTop5ThumbUserByPictureId(TopThumbUserRequest topThumbUserRequest) {
        // 查询前五用户
        Long pictureId = topThumbUserRequest.getPictureId();
        Integer limit = topThumbUserRequest.getLimit();
        String key = PICTURE_LIKE_KEY + pictureId;
        Set<String> top5UserCache = stringRedisTemplate.opsForZSet().range(key, 0, limit);
        if (CollUtil.isEmpty(top5UserCache)) {
            return Collections.emptyList();
        }

        List<Long> idList = top5UserCache.stream().map(Long::valueOf).collect(Collectors.toList());
        // 查询用户信息
        String idStr = StrUtil.join(",", idList);
        return userService.lambdaQuery()
                .in(User::getId, idList)
                .last(String.format("order by field(id, %s)", idStr))
                .list();
    }


    @Override
    public boolean deletePicture(Long id, User loginUser) {
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR, "没有权限");
        // 查询图片
        Picture pictureDb = this.getById(id);
        ThrowUtils.throwIf(pictureDb == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        // 校验权限
        // pictureService.checkSpaceAuth(pictureDb, loginUser);


        // 事务
        transactionTemplate.execute(status -> {
            boolean delete = this.removeById(id);
            ThrowUtils.throwIf(!delete, ErrorCode.OPERATION_ERROR, "删除失败");

            // 判断是否私人空间
            if (pictureDb.getSpaceId() != null) {
                // 释放资源
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, pictureDb.getSpaceId())
                        .setSql("total_count = total_count - 1")
                        .setSql("total_size = total_size - " + pictureDb.getPicSize())
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "更新空间失败");
            }

            // 删除图片关联评论
            Db.lambdaUpdate(PictureComment.class)
                    .eq(PictureComment::getPictureId, id)
                    .remove();

            // 删除redis信息
            // 查询粉丝id
            List<Long> followingIdList = userFollowService.lambdaQuery()
                    .eq(UserFollow::getFollowedUserId, pictureDb.getUserId())
                    .list()
                    .stream()
                    .map(UserFollow::getFollowingUserId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(followingIdList)) {
                for (Long followingId : followingIdList) {
                    String key = PICTURE_FEED_KEY + followingId;
                    // 推送消息
                    stringRedisTemplate.opsForZSet().remove(key, pictureDb.getId().toString());
                }
            }

            return true;
        });
        // 删除图片cos
        this.deletePictureCos(pictureDb);

        // 删除redis图片点赞数据
        String key = PICTURE_LIKE_KEY + id;
        stringRedisTemplate.delete(key);
        return true;
    }

    @Override
    public List<String> searchLikePicture(PictureSearchRequest pictureSearchRequest, User loginUser) {
        // 格式化数量 最多30条
        int count = 60;
        // 要抓取的地址
        String fetchUrl = String.format("https://cn.bing.com/images/search?q=%s&mmasync=1", pictureSearchRequest.getSearchText());
        // 开始抓取
        Document document = null;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片抓取失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        ThrowUtils.throwIf(div == null, ErrorCode.PARAMS_ERROR, "未找到图片");
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;
        // 初始化数组
        Set<String> imgUrlList = new HashSet<>(count);
        // 遍历图片
        for (Element imgElement : imgElementList) {
            String src = imgElement.attr("src");
            if (StrUtil.isBlank(src)) {
                log.error("图片地址为空");
                continue;
            }
            //     处理图片上传地址 ？
            String fileUrl = src.substring(0, src.indexOf("&"));
            imgUrlList.add(fileUrl);
            if (uploadCount++ > count) {
                break;
            }
        }
        return new ArrayList<>(imgUrlList);

    }

    @Override
    public Picture getPictureById(Long id) {
        //     使用互斥锁
        String key = PICTURE_DETAIL_KEY + id;
        String pictureCache = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(pictureCache)) {
            return JSONUtil.toBean(pictureCache, Picture.class);
        }
        if ("".equals(pictureCache)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        }

        //     获取锁
        Picture picture = null;
        try {
            boolean lock = tryLock(id);
            if (lock) {
                //     构建缓存
                picture = this.getById(id);
                //      存储缓存 空数据 防止缓存穿透
                if (picture == null) {
                    stringRedisTemplate.opsForValue().set(key, "", PICTURE_DETAIL_TTL, TimeUnit.MINUTES);
                    throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
                }
                stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(picture), PICTURE_DETAIL_TTL, TimeUnit.MINUTES);
            } else {
                //     休眠 50ms 继续尝试获取锁
                Thread.sleep(50);
                return getPictureById(id);
            }
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, e.getMessage());
        } finally {
            unLock(id);
        }
        return picture;
    }

    @Override
    public Picture getPictureByIdByLogic(Long id) {
        // 采用逻辑过期
        String key = "picture:detail:logic:" + id;
        // 查询redis
        String pictureCache = stringRedisTemplate.opsForValue().get(key);
        // 判断是否为空 直接返回
        if (StrUtil.isBlank(pictureCache)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        }
        // 不为空 查询是否过期
        LogicExpire logicExpire = JSONUtil.toBean(pictureCache, LogicExpire.class);
        Picture picture = JSONUtil.toBean((JSONObject) logicExpire.getEntity(), Picture.class);

        LocalDateTime expireTime = logicExpire.getExpireTime();
        // 未过期 返回
        if (expireTime.isAfter(LocalDateTime.now())) {
            return picture;
        }
        // 过期 获取锁 新建独立线程 查询数据库
        try {
            boolean lock = tryLock(id);
            if (lock) {
                CompletableFuture.runAsync(() -> {
                    savePictureWithLogicTime(id, 10);
                });
            }

            return picture;
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "构建缓存失败");
        } finally {
            unLock(id);
        }
    }

    @Override
    public void savePictureWithLogicTime(Long id, Integer ttl) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime time = now.plusMinutes(ttl);
        String key = "picture:detail:logic:" + id;
        Picture picture = this.getById(id);
        stringRedisTemplate
                .opsForValue()
                .set(key, JSONUtil.toJsonStr(new LogicExpire<>(time, picture)));
    }

    @Override
    public Page<SoImageSearchResult> searchSimilarImageByUrl(SearchPictureByPictureRequest searchPictureByPictureRequest) {
        // 校验地址是否合法
        String url = searchPictureByPictureRequest.getUrl();
        int current = searchPictureByPictureRequest.getCurrent();
        int pageSize = 20;
        validUrlInfo(url);
        // 调用搜图api
        Page<SoImageSearchResult> soImageSearchResultPage = new Page<>();
        int start = (current - 1) * pageSize;
        List<SoImageSearchResult> soImageSearchResults = SoImageSearchApiFacade.searchImage(url, start);

        soImageSearchResultPage.setRecords(soImageSearchResults);
        soImageSearchResultPage.setTotal(pageSize);
        return soImageSearchResultPage;
    }

    @Override
    public PictureTagCategory listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意", "默认标签");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报", "默认分类");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return pictureTagCategory;
    }

    @Override
    public Map<String, Page<PictureVO>> listPictureVOByPage() {
        //     获取分类
        Map<String, Page<PictureVO>> res = new HashMap<>();
        PictureTagCategory pictureTagCategory = listPictureTagCategory();
        List<String> categoryList = pictureTagCategory.getCategoryList();
        int current = 1;
        int pageSize = 12;
        PictureQueryRequest pictureQueryRequest = new PictureQueryRequest();
        // 封装首页信息1-5页
        for (int i = 1; i <= 3; i++) {
            pictureQueryRequest.setCategory("");
            pictureQueryRequest.setCurrent(i);
            addPage(pictureQueryRequest, res);
            // 普通用户只能查询审核通过的图片
        }
        //     封装数据
        return res;
    }


    @Override
    public Page<ImageExpansion> getExpandedImageList(PageRequest pageRequest) {
        long userId = StpKit.SPACE.getLoginIdAsLong();
        Page<ImageExpansion> page = imageExpansionService.lambdaQuery()
                .eq(ImageExpansion::getUserId, userId)
                .orderByDesc(ImageExpansion::getCreateTime)
                .page(new Page<>(pageRequest.getCurrent(), pageRequest.getPageSize()));
        // 新线程查询未完成的任务
        CompletableFuture.runAsync(() -> {
            page.getRecords().stream()
                    .filter(imageExpansion -> imageExpansion.getStatus().equals(ExpansionStatus.PROCESSING.getCode()))
                    .forEach(imageExpansion -> {
                        // 执行异步任务
                        GetImageOutPaintingResponse imageOutPainting = aliYunAiApi.getImageOutPainting(imageExpansion.getTaskId());
                        GetImageOutPaintingResponse.Task output = imageOutPainting.getOutput();
                        if (output.getTaskStatus().toString().equals("RUNNING")) {
                            // 任务正在执行
                            System.out.println("执行中");
                        } else if (output.getTaskStatus().toString().equals("SUCCEEDED")) {
                            String outputImageUrl = output.getOutputImageUrl();
                            // 下载文件
                            // 上传文件地址
                            String uploadPrefix = "expand";
                            // 创建临时文件
                            File tempFile = null;
                            try {
                                tempFile = File.createTempFile(uploadPrefix, "");
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            HttpUtil.downloadFile(outputImageUrl, tempFile);
                            // 上传文件
                            String url = cosManager.uploadFile(uploadPrefix, FileUtil.getName(outputImageUrl), tempFile);
                            boolean update = imageExpansionService.lambdaUpdate()
                                    .eq(ImageExpansion::getId, imageExpansion.getId())
                                    .set(ImageExpansion::getStatus, ExpansionStatus.SUCCESS.getCode())
                                    .set(ImageExpansion::getExpandedPictureUrl, url)
                                    .update();
                            ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "更新失败");

                        } else {
                            boolean update = imageExpansionService.lambdaUpdate()
                                    .eq(ImageExpansion::getId, imageExpansion.getId())
                                    .set(ImageExpansion::getStatus, ExpansionStatus.FAILED.getCode())
                                    .set(ImageExpansion::getErrorMessage, "任务失败")
                                    .update();
                            ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "更新失败");
                        }
                    });
        });
        return page;
    }


    private void addPage(PictureQueryRequest pictureQueryRequest, Map<String, Page<PictureVO>> res) {
        int pageSize = pictureQueryRequest.getPageSize();
        int current = pictureQueryRequest.getCurrent();
        pictureQueryRequest.setCurrent(pictureQueryRequest.getCurrent());
        pictureQueryRequest.setPageSize(pageSize);
        pictureQueryRequest.setTags(Collections.emptyList());
        pictureQueryRequest.setSortField("create_time");
        pictureQueryRequest.setSortOrder("descend");
        pictureQueryRequest.setReviewStatus(null);
        // 参数MD5
        String jsonStr = JSONUtil.toJsonStr(pictureQueryRequest);
        String token = DigestUtils.md5DigestAsHex(jsonStr.getBytes());
        // 普通用户只能查询审核通过的图片
        pictureQueryRequest.setReviewStatus(ReviewStatusEnum.PASSED.getValue());
        QueryWrapper<Picture> queryWrapper = this.getQueryWrapper(pictureQueryRequest);

        Page<Picture> picturePage = this.page(new Page<>(current, pageSize), queryWrapper);

        Page<PictureVO> pictureVOPage = this.listPictureVOByPage(picturePage);
        res.put(token, pictureVOPage);
    }


    private void fillNameRuleInfo(Picture picture, String nameRule, int count) {
        try {
            if (nameRule.contains("{序号}")) {
                picture.setName(nameRule.replaceAll("\\{序号}", String.valueOf(count)));
                return;
            }

            if (StrUtil.isNotBlank(nameRule)) {
                picture.setName(nameRule);
            }

        } catch (Exception e) {
            log.info("填充命名规则信息失败", e);
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "命名规则错误");
        }
    }


    // 获取锁
    public boolean tryLock(Long id) {
        String key = PICTURE_LOCK_KEY + id;
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", ONE_TIME_TTL * 5L, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }

    public void unLock(Long id) {
        String key = PICTURE_LOCK_KEY + id;
        stringRedisTemplate.delete(key);
    }
}




